﻿using UnityEngine;

public class SetRenderQueue : MonoBehaviour
{
	//public int renderQueue = 3000;
	public UIPanel panelCheck;
	public UIWidget widgetCheck;
	public int front = 1;
	public bool autoSetFromStart = true;

	Material mMat;
	bool bInit = false;
	bool bSetMenual = false;
	void Start ()
	{
	//	InitRenderQueue();
		if(autoSetFromStart)
			InitRenderQueue();
	}

	public void InitRenderQueue()
	{
		if(bInit)
			return;

		Renderer ren = renderer;
		
		if (ren == null)
		{
			ParticleSystem sys = GetComponent<ParticleSystem>();
			if (sys != null) ren = sys.renderer;
		}
		
		if (ren != null)
		{

			int maxRenderQueue = 0;
			int baseRenderQueue = 3000;
			if(panelCheck!=null)
			{
				mMat = new Material(ren.sharedMaterial);
				UIWidget [] widgets = panelCheck.gameObject.GetComponentsInChildren<UIWidget>();
				foreach( UIWidget widget in widgets)
				{
					baseRenderQueue = widget.material.renderQueue;
					if( widget.drawCall.renderQueue> maxRenderQueue)
						maxRenderQueue = widget.drawCall.renderQueue;
					glog.debug(widget.name+"   "+baseRenderQueue+"  rq = "+widget.drawCall.renderQueue);
				}
				
				mMat.renderQueue = baseRenderQueue + maxRenderQueue + front;
				ren.material = mMat;
			}
			else if(widgetCheck!=null)
			{
				mMat = new Material(ren.sharedMaterial);
				mMat.renderQueue = widgetCheck.material.renderQueue + widgetCheck.drawCall.renderQueue + front;
				ren.material = mMat;
			}
		}
		bInit = true;
	}

	public void SetRenderQueueManual()
	{
		if(bSetMenual)
			return;


		int maxRenderQueue = 0;
		int baseRenderQueue = 3000;
		if(panelCheck!=null)
		{
			ParticleSystem sys = GetComponent<ParticleSystem>();
			UIWidget [] widgets = panelCheck.gameObject.GetComponentsInChildren<UIWidget>();
			foreach( UIWidget widget in widgets)
			{
				baseRenderQueue = widget.material.renderQueue;
				if( widget.drawCall != null && widget.drawCall.renderQueue> maxRenderQueue)
					maxRenderQueue = widget.drawCall.renderQueue;
				//glog.debug(widget.name+"   "+baseRenderQueue+"  rq = "+widget.drawCall.renderQueue);
			}
			
			sys.renderer.material.renderQueue = baseRenderQueue + maxRenderQueue + 1;
		}
		bSetMenual = false;
	}
	
	void OnDestroy () { if (mMat != null) Destroy(mMat); }
}